import os
import sqlite3

from newsblog.VIP.tbitems_db import *
from newsblog.VIP.tbitems import *

# 打开数据库
from web.settings import BASE_DIR


def opendb():
    dbpath = os.path.join(BASE_DIR, 'templates\\tb.db')
    conn = sqlite3.connect(dbpath)
    cursor = conn.cursor()


# 关闭数据库
def closedb(conn,cursor):
    conn.commit()
    cursor.close()


#存入数据库
def savemain(itemid,page):
    print(f'{itemid}和页码是{page}')
    # itemid = 588976817331
    # page = 2
    JSONlist=[]
    JSONlist=tbmain(itemid, page)  #爬虫request 获取到一个页面评论的json信息
    # print(JSONlist)
    # 获取到list开始循环获得资源
    dbpath = os.path.join(BASE_DIR, 'templates\\tb.db')
    conn = sqlite3.connect(dbpath)
    cursor = conn.cursor()
    for i in JSONlist:
        if i['评论内容'] == '此用户没有填写评价。':
            continue
        try:
            initdb(cursor)  #如果没有则创建sql表
            insertdb(cursor,
                                itemid,
                                i['评论人'],
                                i['评论头像'],
                                i['评论时间'],
                                i['评论内容'],
                                i['购买商品类型'],
                                str(i['评论视频截图']),
                                str(i['评论视频']),
                                str(i['好评图片']))
        except Exception as e:
            print(e)
            print('数据库插入错误')
            pass
    closedb(conn, cursor)



#读取数据库内容
def readinfo(id):
    text = []
    dbpath = os.path.join(BASE_DIR, 'templates\\tb.db')
    conn = sqlite3.connect(dbpath)
    cursor = conn.cursor()
    try:
        JSONlist = searchID(cursor,id)
        # print(list(JSONlist[0]))
        # for i in JSONlist:
        #     print(i[4])
        #     text.append(i[4])
        # print(JSONlist)
        return JSONlist
    except Exception as e:
        print(e)
        #没有查到记录
        print("数据库没有该记录")
    # print(text)
    closedb(conn, cursor)


# readinfo()
# main(521551373783,11)
# for i in range(20):
#     i=i+1
#     # if i <= 12:
#     #     continue
#     main(521551373783,i)
#     print(i)
#     sqlite3.time.sleep(3)